package com.yixun.qfbao.hander;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.PremisesRecommenderService;
import com.yixun.qfbao.apidto.BatchUpdateCaseMemberPremisesDto;
import com.yixun.qfbao.apidto.BindPartnerToPremisesResDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.constant.RedisKeyConstant;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.MechanismStatusEnum;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.vo.BatchUpdateCaseMemberPremisesVo;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: channel-parent
 *
 * @description: 设置楼盘驻场
 *
 * @author: Seven.wang
 *
 * @create: 2020-9-17 15:21:48
 **/
@Service("addPremisesDefendHander")
public class AddPremisesDefendHander extends CommonAbstractHander {

    private static Logger log = Logger.getLogger(AddPremisesDefendHander.class);

    @Autowired
    PremisesRecommenderService premisesRecommenderService;
    @Autowired
    PremisesService premisesService;

    @Autowired
    CaseMemberService caseMemberService;

    @Override
    public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
        BatchUpdateCaseMemberPremisesVo reqVo = (BatchUpdateCaseMemberPremisesVo)reqDto;
        BatchUpdateCaseMemberPremisesDto reqDto1 = reqVo.getParams();
        BaseResponseDTO res = new BaseResponseDTO<BindPartnerToPremisesResDto>();

        if(CollectionUtils.isEmpty(reqDto1.getPremisesIds())){
            res.setResult(ResultEnum.FAIL.getNo());
            res.setErrorMsg("楼盘异常，请刷新后重试！");
            return res;
        }
        try {
            //查询在售楼盘相关驻守经纪人
            CaseMemberDto cmDto = new CaseMemberDto();
            cmDto.setPremisesId(reqDto1.getPremisesIds().get(0));
            cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
            List<CaseMemberDto> oldList = caseMemberService.selectParAndPreListByDto(cmDto);

            Premises premises = premisesService.selectById(reqDto1.getPremisesIds().get(0));
            List<CaseMemberDto> addList = new ArrayList<>();
            List<CaseMemberDto> requestList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(reqDto1.getUserIds())){
                addList = buildAddPremisesCaseMemberList(reqDto1, oldList, premises);
                // 构建页面传递的驻守经纪人列表
                requestList = buildRequestPremisesDefendList(reqDto1, premises);
            }

            // 构建需删除的驻守经纪人列表
            List<CaseMemberDto> removeList = buildRemovePremisesDefendList(requestList, oldList);
            if(CollectionUtils.isNotEmpty(oldList) && CollectionUtils.isNotEmpty(removeList)){
                caseMemberService.batchDeleted(removeList);
                for(CaseMemberDto caseMemberDto: removeList){
                    // 清除此用户的楼盘权限
                    String redisKey = RedisKeyConstant.Permission.DEV_USER_PREMISES_PERMISSION + caseMemberDto.getPartnerId();
                    RedisUtil.delete(redisKey);
                }
            }
            if(CollectionUtils.isNotEmpty(addList)){
                caseMemberService.batchAdd(addList);
                for(CaseMemberDto caseMemberDto: addList){
                    // 清除此用户的楼盘权限
                    String redisKey = RedisKeyConstant.Permission.DEV_USER_PREMISES_PERMISSION + caseMemberDto.getPartnerId();
                    RedisUtil.delete(redisKey);
                }
            }
            log.info("addPremisesDefendHander is [success]: 【Parame】："+ JSONObject.toJSONString(reqDto1));

            res.setResult(ResultEnum.SUCCESS.getNo());
            res.setErrorMsg("设置成功!");
        }catch (Exception e) {
            log.info("AddPremisesRecommenderHander is error: {}", e);
            res.setResult(ResultEnum.FAIL.getNo());
            res.setErrorMsg("设置驻场失败!");
        }
        return res;
    }

    /**
     *  构建新增的推荐人列表
     * @param dto
     * @param oldList
     * @return
     */
    private List<CaseMemberDto> buildAddPremisesCaseMemberList(BatchUpdateCaseMemberPremisesDto dto, List<CaseMemberDto> oldList, Premises premises){
        List<CaseMemberDto> list = new ArrayList<>();
        List<Long> userIds = dto.getUserIds();
        Set<Long> userSet = new HashSet<>(userIds);
        for(Long rid : userSet){
            // 是否是新增的驻守
            boolean isPass = true;
            // 如果没有添加过推荐人，则全部为新增的推荐人
            if(CollectionUtils.isNotEmpty(oldList)){
                for(CaseMemberDto op : oldList){
                    // 如果已在推荐人列表存在,则不重复添加
                    if(rid.equals(op.getPartnerId())){
                        isPass = false;
                        break;
                    }
                }
            }
            if(!isPass){
                continue;
            }
            CaseMemberDto entity = new CaseMemberDto();
            entity.setPartnerId(rid);
            entity.setPremisesId(premises.getId());
            entity.setPremisesName(premises.getName());
            entity.setCompanyId(premises.getCompanyId());
            entity.setSmsStatus("1");
            entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
            list.add(entity);
        }
        return list;
    }

    /**
     *  构建页面传值列表
     * @param dto
     * @return
     */
    private List<CaseMemberDto> buildRequestPremisesDefendList(BatchUpdateCaseMemberPremisesDto dto, Premises premises){
        List<CaseMemberDto> list = new ArrayList<>();
        List<Long> userIds = dto.getUserIds();
        Set<Long> userSet = new HashSet<>(userIds);
        for(Long rid : userSet){
            CaseMemberDto entity = new CaseMemberDto();
            entity.setPartnerId(rid);
            entity.setPremisesId(premises.getId());
            entity.setPremisesName(premises.getName());
            entity.setCompanyId(premises.getCompanyId());
            entity.setSmsStatus("1");
            entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
            list.add(entity);
        }
        return list;
    }

    /**
     *  构建需删除的推荐人列表
     * @param oldList
     * @return
     */
    private List<CaseMemberDto> buildRemovePremisesDefendList(List<CaseMemberDto> requestList, List<CaseMemberDto> oldList){
        List<CaseMemberDto> removePremisesDefendList = new ArrayList<>();
        for(CaseMemberDto op : oldList){
            boolean needRemove = true;
            // 如果新增推荐人为空，则取消所有推荐人
            if(CollectionUtils.isNotEmpty(requestList)){
                for (CaseMemberDto np : requestList){
                    if(np.getPartnerId().equals(op.getPartnerId())){
                        needRemove = false;
                        break;
                    }
                }
            }
            if(needRemove){
                removePremisesDefendList.add(op);
            }
        }
        return removePremisesDefendList;
    }

}
